import express from 'express'
import request from '../../util/request.js';
import getToken from './getAccessToken.js';
import subscribeMsgTempl from './subscribeMsgTempl.js';
var router = express.Router()

export const handleSendMessage = async (payload) => {
  return new Promise(async (resolve, reject) => {
    const appletParams = {
      appid: process.env.MINIAPPID,
      secret: process.env.MINISECRET
    }

    const { openid, template_id, data } = payload
    const cData = subscribeMsgTempl(data)[template_id]
    try {
      const rows = await getToken(appletParams)

      request.post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${rows.access_token}`, {
        touser: openid,
        template_id: template_id,
        data: cData,
        page: 'pages/order/detail'
      }).then((result) => {
        if (result.errcode == 0) {
          resolve()
        } else {
          reject(result.errmsg)
        }
      })
    } catch (error) {
      reject(error)
    }
  })
}

router.post('/sendMessage', async (req, res, next) => {
  try {
    await handleSendMessage(req.body)
    res.json(req.app.locals.success('发送成功'))
  } catch (error) {
    console.log('error: ', error);
    res.json(req.app.locals.error(error))
  }

})

export default router
